/**
 * Coryright 2015-2020 www.eyaomall.cn
 * All rights reserved.
 * @author yuhuafeng
 * @date 2016年9月22日
 *
 */

package com.eyaomall.wxmall.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eyaomall.wxmall.common.util.DateUtils;
import com.eyaomall.wxmall.dao.WebLogDao;
import com.eyaomall.wxmall.dao.WebStatisticDao;
import com.eyaomall.wxmall.model.po.WebLog;
import com.eyaomall.wxmall.model.po.WebStatistic;
import com.eyaomall.wxmall.service.WebStatisticService;
import com.lycheeframework.core.common.util.StringUtil;

/**
 * 页面流量分析服务
 * 
 * @author yuhuafeng
 *
 */
@Service
public class WebStatisticServiceImpl implements WebStatisticService {
	
	@Autowired
	private WebLogDao webLogDao;
	
	@Autowired
	private WebStatisticDao webStatisticDao;
	/**
	 * 页面流量采集服务
	 * 
	 * @param log
	 * @return
	 */
	public boolean collect(WebLog log) {

		// 校验数据合法性
		if (StringUtil.isEmpty(log.getTitle()) || StringUtil.isEmpty(log.getIp()) || StringUtil.isEmpty(log.getUrl())
				|| log.getShopId() <= 0|| log.getMemberId() <= 0)
			return false;
		
		//查询日志表，此处应该使用缓存解决性能问题
		WebLog log_last=webLogDao.getLastLogByUrlAndMemberId(log.getUrl(),log.getMemberId());
		WebStatistic statistic=new WebStatistic();
		statistic.setDateRef(DateUtils.dateFormat(new Date()));
		statistic.setTitle(log.getTitle());
		statistic.setShopId(log.getShopId());
		statistic.setUrl(log.getUrl());
		if(log_last==null||DateUtils.compare(log_last.getGmtCreate())){
			statistic.setPv(1);
			statistic.setUv(1);
		}else{
			statistic.setPv(1);
			statistic.setUv(0);
		}
		addResult(statistic);
		//保存进入log表
		webLogDao.insert(log);
		return true;
	}
	
	/**
	 * 增加统计结果，由于精准的要求不高，不设置返回值
	 * @param statistic
	 */
	public void addResult(WebStatistic statistic){
		//查询结果统计是否存在
		WebStatistic tmp=(WebStatistic) webStatisticDao.query(statistic);
		if(tmp==null){
			webStatisticDao.insert(statistic);
		}else{
			webStatisticDao.update("addResult",statistic );
		}
	}
}
